package com.lhf.novel.sysuser.security;

import com.alibaba.fastjson.JSONObject;
import com.lhf.novel.sysuser.po.LoginPerPo;
import com.lhf.novel.sysuser.po.LoginPo;
import com.lhf.novel.sysuser.vo.LoginSuccessVo;
import com.lhf.novel.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * SuccessHandler实体类
 *
 * @author zy 刘会发
 * @since 2020/3/9$
 */
@Component
public class SuccessHandler implements AuthenticationSuccessHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(SuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        LoginPo user = (LoginPo) authentication.getPrincipal();
        request.getSession().setAttribute("uid",user.getId());
        LOGGER.info("登陆成功:" + user.getUsername());
        List<LoginPerPo> perPos = user.getRoles().stream().flatMap(item -> item.getMenus().stream()).collect(Collectors.toList());
        //去重
        List<LoginPerPo> distinct = perPos.stream()
                .map(LoginPerPo::getId)
                .distinct()
                .flatMap(item -> perPos.stream()
                        .filter(it -> item.equals(it.getId()))
                        .distinct())
                .collect(Collectors.toList());


//        菜单
        List<LoginPerPo> menus = distinct.stream()
                .filter(item -> item.getParentId().equals(0))
                .peek(item -> item.setChildren(distinct.stream()
                        .filter(it -> it.getParentId().equals(item.getId()))
                        .collect(Collectors.toList())))
                .collect(Collectors.toList());

//        权限
        List<String> roles = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        writer.write(JSONObject.toJSONString(Result.success(new LoginSuccessVo(user.getRealName(), user.getHeadImg(), menus, roles))));
        writer.flush();
        writer.close();
    }
}


